#include "database.h"

database::database()
{
    if (QSqlDatabase::contains("qt_sql_default_connection")==true)
    {
        //直接返回数据库对象,qt_sql_default_connection代表当前数据库连接
        dataBase = QSqlDatabase::database("qt_sql_default_connection");
    }
    else
    {
        // 建立和SQlite数据库的连接
        dataBase = QSqlDatabase::addDatabase("QSQLITE");
        // 设置数据库文件的名字
        dataBase.setDatabaseName("MyDataBase.db");
    }

    if(false == dataBase.open())
    {
        qDebug() << "Error: Failed to connect database." << dataBase.lastError();
    }
    else
    {
        qDebug() <<"open success"<<'\n';
    }
}

database::~database()
{
    dataBase.close();
}

QString database::excuSql(QString sql)
{
    QStringList list = sql.split(' ');
    QSqlQuery sqlQuery;
    QString query;
    if("login" == list[0])
    {
        query = QString("SELECT * FROM user WHERE username = '%1';").arg(list[1]);
        sqlQuery.exec(query);
        if(true == sqlQuery.next())
        {
            query = QString("SELECT * FROM user WHERE username = '%1' AND password = '%2';").arg(list[1]).arg(list[2]);
            sqlQuery.exec(query);
            if(true == sqlQuery.next())
                return QString("login success") + ' ' + sqlQuery.value(2).toString();
            else
                return QString("password error");
        }
        else
        {
            return QString("user no exist");
        }
    }
    else if("regist" == list[0])
    {
        query = QString("INSERT INTO user VALUES ('%1','%2','北京市');").arg(list[1]).arg(list[2]);
        qDebug()<<query;
        sqlQuery.exec(query);
        return QString("regist success");
    }
    else if("select" == list[0])
    {
        query = QString("SELECT city FROM user WHERE username = '%1';").arg(list[1]);
        sqlQuery.exec(query);
        if(true == sqlQuery.next())
        {
            qDebug()<<sqlQuery.value(0).toString();
            return sqlQuery.value(0).toString();
        }
    }
    else if("changeP" == list[0])
    {
        query = QString("UPDATE user SET password = '%2' WHERE username = '%1';").arg(list[1]).arg(list[2]);
        sqlQuery.exec(query);
        return QString("change password success");
    }
    else if("changeC" == list[0])
    {
        query = QString("UPDATE user SET city = '%2' WHERE username = '%1';").arg(list[1]).arg(list[2]);
        sqlQuery.exec(query);
        return QString("change city success");
    }
}
